package Thread.New.带返回值的线程创建.线程工具;

import java.util.concurrent.Semaphore;

public class Semphore_Use {
    //创建2个许可证
    static Semaphore semaphore = new Semaphore(2);

    public static void main(String[] args) {
        System.out.println("开始执行线程\n-----------------------");
        //同时开启4个子线程运行
        for (int i = 0; i < 4; i++) {
            SubThread subThread = new SubThread();
            subThread.start();
        }
    }

    static class SubThread extends Thread {
        @Override
        public void run() {
            try {
                //执行任务前获取许可证
                semaphore.acquire();
                System.out.println(getName() + "获取许可证,开始执行线程任务");
                sleep(3000);
                //执行完任务释放许可证
                System.out.println(getName() + "线程执行完毕,归还许可证");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

